import { Component, ElementRef, HostListener, OnInit, ViewChild, AfterViewInit, TemplateRef } from '@angular/core';
import { FetchService } from '../../../core/net/fetch.service';
import { NzInputDirective, NzMessageService } from 'ng-zorro-antd';
import * as _ from 'lodash';
import { UtilService } from '../../../core/util/util.service';
import * as moment from 'moment';
import { ActivatedRoute, Router } from '@angular/router';
import { DispatchPlanService } from '../dispatch-plan.service';
import {NzModalRef, NzModalService} from "ng-zorro-antd/modal";

const initialAvg = {
    id: 'avg',
    m: '平均流量',
    val1: null,
    val2: null,
    val3: '-',

    val6: null,
    val7: null,
    val8: null,
    val9: '-',
    val10: null,
    val11: '-',
    val12: '-',
    val13: null,
    val14: null
};
const initialTotal = {
    id: 'total',
    m: '合计水量',
    val1: null,
    val2: '-',
    val3: null,

    val6: null,
    val7: '-',
    val8: '-',
    val9: null,
    val10: null,
    val11: null,
    val12: null,
    val13: null,
    val14: null
};
const intlTableData = [
    {
        id: 1,
        m: '11',
        val1: null,
        val2: null,
        val3: null,

        val6: null,
        val7: null,
        val8: null,
        val9: null,
        va10: null,
        va11: null,
        va12: null,
        va13: null,
        va14: null
    },
    {
        id: 2,
        m: '12',
        val1: null,
        val2: null,
        val3: null,
        val6: null,
        val7: null,
        val8: null,
        val9: null,
        va10: null,
        va11: null,
        va12: null,
        va13: null,
        va14: null
    },
    {
        id: 3,
        m: '1',
        val1: null,
        val2: null,
        val3: null,
        val6: null,
        val7: null,
        val8: null,
        val9: null,
        va10: null,
        va11: null,
        va12: null,
        va13: null,
        va14: null
    },
    {
        id: 4,
        m: '2',
        val1: null,
        val2: null,
        val3: null,
        val6: null,
        val7: null,
        val8: null,
        val9: null,
        va10: null,
        va11: null,
        va12: null,
        va13: null,
        va14: null
    },
    {
        id: 5,
        m: '3',
        val1: null,
        val2: null,
        val3: null,
        val6: null,
        val7: null,
        val8: null,
        val9: null,
        va10: null,
        va11: null,
        va12: null,
        va13: null,
        va14: null
    },
    {
        id: 6,
        m: '4',
        val1: null,
        val2: null,
        val3: null,
        val6: null,
        val7: null,
        val8: null,
        val9: null,
        va10: null,
        va11: null,
        va12: null,
        va13: null,
        va14: null
    },
    {
        id: 7,
        m: '5',
        val1: null,
        val2: null,
        val3: null,
        val6: null,
        val7: null,
        val8: null,
        val9: null,
        va10: null,
        va11: null,
        va12: null,
        va13: null,
        va14: null
    },
    {
        id: 8,
        m: '6',
        val1: null,
        val2: null,
        val3: null,
        val6: null,
        val7: null,
        val8: null,
        val9: null,
        va10: null,
        va11: null,
        va12: null,
        va13: null,
        va14: null
    },
    {
        id: 'avg',
        m: '平均流量',
        val1: null,
        val2: null,
        val3: '-',
        val6: null,
        val7: null,
        val8: null,
        val9: '-',
        val10: null,
        val11: '-',
        val12: '-',
        val13: null,
        val14: null
    },
    {
        id: 'total',
        m: '合计水量',
        val1: null,
        val2: '-',
        val3: null,
        val6: null,
        val7: '-',
        val8: '-',
        val9: null,
        val10: null,
        val11: null,
        val12: null,
        val13: null,
        val14: null
    }
];

@Component({
    selector: 'app-slb-dispatch-plan-add',
    templateUrl: './slb-dispatch-plan-add.component.html',
    styleUrls: ['./slb-dispatch-plan-add.component.scss']
})
export class SlbDispatchPlanAddComponent implements OnInit , AfterViewInit {
    widthConfig = ['100px', '100px', '100px',
    '100px', '100px', '100px', '100px', '100px',
    '100px', '100px', '100px', '100px', '100px'];
    scrollConfig =  {
        x: '1300px', y: '400px'
    };
    pageType: string;   //  add edit detail
    planName = '';
    editableTableData = [];
    valArr = ['val1', 'val2', 'val3', 'val6', 'val7', 'val8', 'val9', 'val10', 'val11', 'val12', 'val13', 'val14'];
    mArr = [11, 12, 1, 2, 3, 4, 5, 6];
    year = moment().add(1, 'y').year();    // 默认查后一年
    editId: string | null;
    editCache: { [key: string]: { edit: boolean; data: any } } = {};
    // 文件预览
    file = null;
    tplModal: NzModalRef;
    fileSrc = '';
    fileType = '';
    fileId = '';
    fileTypeList = ['pdf', 'png', 'jpg'];
    @ViewChild(NzInputDirective, {read: ElementRef}) inputElement: ElementRef;
    @ViewChild('wrap') elementView: ElementRef;
    @HostListener('window:click', ['$event'])
    handleClick(e: MouseEvent): void {
        if (this.inputElement && e.target['tagName'] !== 'INPUT') {
            Object.keys(this.editCache).forEach(key => {
                this.editCache[key].edit = null;
            });
            this.calcTableData(this.editableTableData, 'avg');
            this.calcTableData(this.editableTableData, 'total');
        }
    }

    constructor(
        private fetchService: FetchService,
        private util: UtilService,
        private routerInfo: ActivatedRoute,
        private router: Router,
        private message: NzMessageService,
        private dispatchService: DispatchPlanService,
        private modal: NzModalService,
    ) {
        this.year = this.routerInfo.snapshot.queryParams['year'] || moment().add(1, 'y').year();
        this.pageType = this.routerInfo.snapshot.queryParams['type'];
        this.planName = this.routerInfo.snapshot.queryParams['name'];
        this.getFileList(this.planName);
    }

    ngOnInit() {
        this.getEditableTableData();
    }
    ngAfterViewInit() {
        this.scrollConfig.y = (this.elementView.nativeElement.offsetHeight - 320) + 'px';
    }
    getEditableTableData(): void {
        // 新增状态 默认查询 后一年 计划
        this.editableTableData = _.cloneDeep(intlTableData);
        console.log("this.editableTableData-1", this.editableTableData);
        this.fetchService.post<any>('plan/wrsReportData/query', {
            reportId: 1,
            y: this.year,
        }).subscribe(res => {
            // 新增状态 自动补齐 planName
            if (this.pageType === 'add' || !this.planName ) {
                this.planName = `${moment().year()}年11月-${moment().year() + 1}年6月黄河干流水量调度计划`;
                if (Array.isArray(res) && res.length) {
                    this.message.warning(`${this.planName} 已创建,请编辑`);
                }
            }

            const cacheArr: Array<any> = ['平均日流量', '水量合计'];
            this.mArr = _.concat(this.mArr, cacheArr);
            if (Array.isArray(res) && res.length) {
                this.editableTableData = res.concat(initialAvg, initialTotal);
                this.calcTableData(this.editableTableData, 'avg');
                this.calcTableData(this.editableTableData, 'total');
                this.updateEditCache();
            }
        });
        this.updateEditCache();
    }
    updateEditCache(): void {
        this.editableTableData.forEach(item => {
            this.editCache[item.id] = {
                edit: false,
                data: {...item}
            };
        });
    }

    startEdit(id: string, event: MouseEvent): void {
        event.preventDefault();
        event.stopPropagation();
        this.editCache[id].edit = true;
        this.editId = id;
    }

    isEditableTd(id): boolean {
        if (this.pageType !== 'detail') {
            //  所选年份大于当前年份 才可以编辑
            return this.editCache[id].edit && id !== 'avg' && id !== 'total';
        } else {
            return false;
        }
    }

    calcTableData(res, id): any {
        const obj = _.find(res, o => {
            return o['id'] === id;
        });
        const index = _.findIndex(res, o => {
            return o['id'] === id;
        });
        const keyArr = Object.keys(obj);
        const list = _.dropRight(res, 2);
        keyArr.forEach((key, i) => {
            //  key以val开头 且值不为'-'
            if (key.slice(0, 3) === 'val' && obj[key] !== '-') {
                const feb = this.dispatchService.isLeapyear(this.year) ? 29 : 28;
                const days = 30 + 31 + 31 + feb + 31 + 30 + 31 + 30 ;
                const valList = this.util.getItemValues(list, key, true);
                const flow = valList[0] * 30 + valList[1] * 31 + valList[2] * 31 + valList[3] * feb + valList[4] * 31 + valList[5] * 30 + valList[6] * 31 + valList[7] * 30;
                if (id === 'avg') {
                    obj[key] = this.dispatchService.keepTwoDecimalFull(flow / days);
                } else if (id === 'total') {
                    // 水量
                    if ([2, 7, 11, 14, 15].includes(i)) {
                        obj[key] = this.dispatchService.getWaterByFlowYi(flow);
                    } else {
                        obj[key] = this.dispatchService.keepTwoDecimalFull(this.util.sum(this.util.getItemValues(list, key, true)));
                    }
                }
            }
        });
        _.fill(res, obj, index, index + 1);
    }

    save() {
        const tableData = _.cloneDeep(this.editableTableData);
        tableData.forEach(row => {
            const valData = [];
            this.valArr.forEach(item => {
                valData.push(row[item]);
            });
            row['val'] = valData;
        });
        const data = tableData.map(item => {
            return _.pick(item, ['m', 'val']);
        });
        console.log(data);
        let flag = false;
        data.some(item => {
            flag = item.val.includes("");
            return flag;
        });
        if (flag) {
            this.message.warning('请填写完所有管理处调度计划再保存');
        } else {
            const params = {
                reportId: 1,
                y: this.year,
                data: JSON.stringify(_.dropRight(data, 2)),
                name: this.planName,
            };
            this.fetchService.post<any>('plan/wrsReportData/add', params).subscribe(res => {
                this.message.success('保存成功');
            });
        }
    }

    goBack(): void {
        this.router.navigate(['/dispatch-plan/MWR-dispatch']);
    }
    isSubmitBtnShow(): boolean {
        return true;
    }
    // 获取 文件目录
    getFileList(key?) {
        const param = {
            docId: 50,
            fileName: key,
            pageNum: 1,
            pageSize: 100
          };
        this.fetchService.post<any>('archives/wrsDocFile/list', param).subscribe(res => {
            if (Array.isArray(res.list)) {
                this.file = res.list[0];
            }
        });
    }
    // 文件预览
    viewFile(file, tplContent: TemplateRef<{}>): void {
        const that = this;
        this.fileType = file.fileName.split('.')[1];
        this.fileId = file.fileId;
        this.fileSrc = `${(window as any).environment.apiBaseUrl}comm/file/view/${file.fileId}`;

        this.tplModal = this.modal.create({
            nzTitle: '文件预览',
            nzContent: tplContent,
            nzWidth: 1100,
            nzFooter: null,
            nzMaskClosable: false,
            nzClosable: true,
            nzOnCancel(): void {
            that.destroyModal();
            }
        });
    }
    destroyModal() {
        this.tplModal.destroy();
    }
}
